<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    @close="closeDialog"
    custom-class="dialog-minwidth"
    width="640px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal-append-to-body="false"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="事项类型：" class="mrT8" prop="typeId">
        <el-select
          class="dialogSingleInp"
          v-model="ruleForm.typeId"
          filterable
          placeholder="请选择"
          clearable
          :disabled="dialogType === 'update' ? true : false"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="(item, index) in eventTypeArr"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="巡查事项：" prop="item">
        <el-input
          class="dialogSingleInp"
          type="textarea"
          rows="3"
          maxlength="30"
          show-word-limit
          placeholder="请输入巡查事项内容"
          clearable
          v-model="ruleForm.item"
        ></el-input>
      </el-form-item>
      <el-form-item label="巡查结果：" prop="resultType">
        <el-select
          class="dialogSingleInp"
          v-model="ruleForm.resultType"
          filterable
          placeholder="请选择巡查结果的填写方式"
          clearable
          @change="changeFillType"
          :popper-append-to-body="false"
        >
          <el-option
            v-for="(item, index) in fillTypeArr"
            :key="index"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结果示例：">
        <template
          v-if="
            fillType === 'TEXT' ||
            fillType === 'POPULATION' ||
            fillType === 'PERCENTAGE' ||
            fillType === 'MONEY' ||
            fillType === 'AMOUNT' ||
            fillType === 'DAYS' ||
            fillType === 'HOURS'
          "
        >
          <el-input type="text" class="dialogSingleInp" disabled></el-input
          >&nbsp;{{ unit }}
        </template>
        <template
          v-else-if="
            fillType === 'SINGLE_CHOOSE' || fillType === 'MULTIPLE_CHOOSE'
          "
        >
          <p v-for="(v, i) in ruleForm.value" :key="i">
            <el-radio
              disabled
              label=""
              v-if="fillType === 'SINGLE_CHOOSE'"
            ></el-radio>
            <el-checkbox
              disabled
              label=""
              v-if="fillType === 'MULTIPLE_CHOOSE'"
            ></el-checkbox>
            <el-form-item
              style="display: inline-block"
              :prop="'value.' + `${i}`"
              :rules="{
                required: true,
                message: '请输入结果展示内容',
                trigger: 'blur',
              }"
            >
              <el-input
                style="width: 366px"
                type="text"
                v-model="ruleForm.value[i]"
              ></el-input>
            </el-form-item>
            <span
              v-if="i > 1"
              style="font-size: 14px; color: #e42722; cursor: pointer"
              class="titleAction"
              @click="delInput(i)"
              >删除</span
            >
          </p>
          <p class="addInput" @click="addInput">
            <span style="font-size: 25px">+</span>
          </p>
        </template>
        <template v-else-if="fillType === 'DATE'">
          <el-date-picker
            type="date"
            disabled
            placeholder="请选择"
            class="dialogSingleHalfInp"
            clearable
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </template>
        <span class="color999" v-else>选择巡查结果后自动带出</span>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="closeDialog" class="cancel">取 消</el-button>
      <el-button
        type="primary"
        class="save"
        @click.native="saveInspectionItems('ruleForm')"
        :loading="loading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'InspectionDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    dialogType: {
      type: String,
      default: '',
    },
    inspectionItemsDetail: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      dialogTitle: '',
      fillType: '',
      eventTypeArr: [],
      fillTypeArr: [],
      ruleForm: {
        typeId: '',
        item: '',
        resultType: '',
        value: [], //结果示例
      },
      rules: {
        typeId: [
          {
            required: true,
            message: '请选择事项类别',
            trigger: 'change',
          },
        ],
        item: [
          {
            required: true,
            message: '请输入巡查事项内容',
            trigger: 'blur',
          },
        ],
        resultType: [
          {
            required: true,
            message: '请选择巡查结果的填写方式',
            trigger: 'change',
          },
        ],
      },
      loading: false,
    }
  },
  async created() {
    await this.getEventType()
    await this.getResultType()
    this.dialogTitle =
      this.dialogType === 'add' ? '添加巡查事项' : '修改巡查事项'
    if (this.dialogType === 'update') {
      this.ruleForm.item = this.inspectionItemsDetail.item
      this.ruleForm.typeId = this.inspectionItemsDetail.typeId
      this.ruleForm.resultType = this.inspectionItemsDetail.resultType
      this.ruleForm.value = JSON.parse(
        JSON.stringify(this.inspectionItemsDetail.value)
      )
      this.fillType = this.inspectionItemsDetail.resultType
    }
  },
  computed: {
    unit() {
      let unitName = null
      switch (this.fillType) {
        case 'TEXT':
          unitName = ''
          break
        case 'POPULATION':
          unitName = '人'
          break
        case 'PERCENTAGE':
          unitName = '%'
          break
        case 'MONEY':
          unitName = '元'
          break
        case 'AMOUNT':
          unitName = '个'
          break
        case 'DAYS':
          unitName = '天'
          break
        case 'HOURS':
          unitName = '小时'
          break
        default:
          break
      }
      return unitName
    },
  },
  methods: {
    closeDialog() {
      this.$emit('closeDialog')
    },
    // 保存巡查事项
    saveInspectionItems(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          let data = JSON.parse(JSON.stringify(this.ruleForm))
          data.value = JSON.stringify(this.ruleForm.value)
          let url = 'api-gov/ipqcItem/base/addItem'
          if (this.dialogType === 'update') {
            Object.assign(data, {
              id: this.inspectionItemsDetail.id,
            })
            data.typeId && delete data.typeId
            url = 'api-gov/ipqcItem/base/modifyItem'
          }
          return this.axios({
            method: 'post',
            url,
            data,
          })
            .then((response) => {
              this.loading = false
              if (!response.data.hasError) {
                this.$message.success('操作成功')
                this.$emit('closeDialog', 'update')
              } else {
                this.$message.error(response.data.errorMsg)
              }
            })
            .catch((error) => {
              this.loading = false
              if (error.response) {
                this.$message.error(error.response.data)
              }
            })
        } else {
          this.$message.error('请按照提示规则输入内容!')
          return false
        }
      })
    },
    // 获取事项类别
    getEventType() {
      return this.axios({
        method: 'get',
        url: 'api-gov/ipqcType/base/findAllTypes',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.eventTypeArr = results
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 获取结果类型
    getResultType() {
      return this.axios({
        method: 'get',
        url: 'api-gov/ipqcItem/base/getAllResultType',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.fillTypeArr = results
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 更改巡查结果类型
    changeFillType(val) {
      if (val === 'SINGLE_CHOOSE' || val === 'MULTIPLE_CHOOSE') {
        if (
          this.dialogType === 'update' &&
          val === this.inspectionItemsDetail.resultType &&
          this.inspectionItemsDetail.value.length > 1
        ) {
          this.ruleForm.value = JSON.parse(
            JSON.stringify(this.inspectionItemsDetail.value)
          )
        } else {
          this.ruleForm.value = ['', '', '']
        }
      }
      this.fillType = val
    },
    addInput() {
      if (this.ruleForm.value.length < 5) {
        this.ruleForm.value.push('')
      }
    },
    delInput(i) {
      this.ruleForm.value.splice(i, 1)
    },
  },
}
</script>

<style scoped lang="less">
/deep/ .el-select {
  // width: 350px !important;
}
/deep/ .el-textarea {
  // width: 350px !important;
  .el-input__count {
    background: none;
  }
}
/deep/ .el-input {
  // width: 350px;
}
/deep/ .el-dialog__body {
  padding-right: 20px;
}

/deep/ .el-radio {
  margin-right: 0;
}
/deep/ .el-checkbox {
  margin-right: 10px;
}
.addInput {
  width: 394px;
  height: 32px;
  text-align: center;
  line-height: 30px;
  font-size: 14px;
  color: #a3a3a3;
  border: 1px dashed #dee5f4;
}
.addInput:hover {
  cursor: pointer;
  color: #409eff;
  border-color: #409eff;
}
</style>
